<template>
  <div class="dispalay-gallery-wrapper">
    <div class="dispalay-gallery-content">
      <div class="content-header">
        <span>选择配电图：</span>
        <Select style="width:200px;"
          v-model="currentGalleryId"
          @on-change="handleChange">
          <Option v-for="(item,index) in galleryList"
            :value="item.id"
            :key="index">{{item.name}}</Option>
        </Select>
        <span v-if="currentDeviceName"
          style="margin-left:10px;">{{currentDeviceName}}</span>
      </div>
      <div class="content-body">
        <div class="body-left"
          ref="takePhoto">
          <vue-draggable-resizable :prevent-deactivation="true"
            classNameDragging="dragable-ing"
            @dragstop="(x,y)=>onDragStop(x,y,item)"
            className="dragable-element"
            :parent="true"
            :resizable="false"
            w="30"
            h="40"
            :x="item.x"
            :y="item.y"
            v-for="(item, index) in playGround"
            :key="index">
            <div class="dragable-inner">
              <div class="div"
                @click.stop.prevent="goBackClassRoom(currentId)"
                v-if="currentId===item.id"
                style="color:#000;">
                <Icon type="md-close-circle" />
              </div>
              <img src="~@/assets/img/current-green.png"
                width="100%;height:100%;"
                class="drag">
            </div>
          </vue-draggable-resizable>
          <img width="100%"
            height="100%"
            :src="currentUrl"
            alt="配电图"
            v-if="currentUrl">
        </div>
        <div class="body-right">
          <div class="tree-wrapper">
            <treeselect v-model="currentId"
              @select="throwToPlayground"
              placeholder="请选择设备..."
              :normalizer="normalizer"
              :flattenSearchResults="true"
              noOptionsText="该企业下无设备列表！"
              noResultsText="没有搜索到目标设备！"
              name="tree-device"
              :multiple="false"
              :clearable="true"
              :always-open="true"
              noChildrenText="该区域下没有设备！"
              :options="classRoom"
              :max-height="465">
            </treeselect>
          </div>
          <!-- :style="{backgroundImage:'url('+currentUrl+')'}" -->
          <div class="image-wrapper"
            v-if="thumbnailImage">
            <img width="100%"
              height="100%"
              :src="thumbnailImage"
              alt="缩略图">
          </div>
        </div>
      </div>
      <div class="content-footer">
        <Button @click="saveFunc">生成缩略图</Button>
      </div>
    </div>
  </div>
</template>
<script>
import '@/styles/display-gallery.scss'

import VueDraggableResizable from 'vue-draggable-resizable'
import html2canvas from 'html2canvas'
import 'vue-draggable-resizable/dist/VueDraggableResizable.css'

import {
  getGalleryDevice,
  getGalleryList,
  genGalleryUrl,
  addPoint,
  removePoint,
  yulanImage
} from '@/api'
import { disposalData } from './material'

const findPlaygound = array => {
  const newArray = []
  array.forEach(t => {
    t.children.forEach(y => {
      if (y.isDisabled) {
        newArray.push(y)
      }
    })
  })
  return newArray
}
export default {
  components: { VueDraggableResizable },
  props: {
    id: {
      type: String,
      default: ''
    }
  },

  watch: {
    id() {
      this.getGalleryList()
    }
  },
  mounted() {
    this.getGalleryList()
  },
  data() {
    return {
      // 图上的点
      playGround: [],
      // 所有设备
      classRoom: [],
      currentId: null,
      galleryList: [],
      currentGalleryId: '',
      currentUrl: '',
      currentDeviceName: null,
      thumbnailImage: null,
      normalizer(node) {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      }
    }
  },
  methods: {
    // 配电图change事件
    handleChange(value) {
      this.thumbnailImage = null
      const imgUrl = this.galleryList.find(t => t.id === value).imgUrl
      // 大众
      this.currentUrl = yulanImage(value)

      // yun3 
      // this.currentUrl = genGalleryUrl(imgUrl)
      this.getGalleryDevice()
    },

    // 放在配电图上
    throwToPlayground(item) {
      if (item.children) {
        return false
      }
      const params = {
        deviceId: item.id,
        distributionId: this.currentGalleryId,
        x: 0,
        y: 0
      }
      addPoint(params).then(res => {
        if (res.code === 200) {
          item['isDisabled'] = true
          this.playGround.push(item)
        }
      })
    },

    // 从配电图上返回select
    goBackClassRoom(id) {
      const vm = this
      const params = { id, distributionId: vm.currentGalleryId }
      removePoint(params).then(res => {
        if (res.code === 200) {
          vm.currentDeviceName = null
          vm.currentId = id
          vm.getGalleryDevice()
        }
      })
      /**
      const newPlayGound = [...vm.playGround]
      // 配电图 通过选中id定位设备
      const index = newPlayGound.findIndex(t => t.id === id)

      // 在配电图删移除该设备
      const result = newPlayGound.splice(index, 1)
      if (result.length === 1) {
        const { groupId } = result[0]
        // 获取区域的索引
        const parentIndex = vm.classRoom.findIndex(t => t.id === groupId)
        // 定位区域
        const parent = vm.classRoom[parentIndex]
        // 通过区域定位设备
        const itemInOptionSIndex = parent.children.findIndex(t => t.id === id)
        vm.$set(
          vm.classRoom[parentIndex].children[itemInOptionSIndex],
          'isDisabled',
          false
        )
        vm.playGround = newPlayGound
        // select 中高亮删除的设备
        vm.currentId = result[0].id
        vm.currentIndex = null
        vm.currentDeviceName = null
        
      } else {
        return false
      }
      return false
       */
    },

    // 操作结束，更新一下配电图 array
    onDragStop(x, y, item) {
      const params = {
        deviceId: item.id,
        distributionId: this.currentGalleryId,
        x,
        y
      }
      addPoint(params).then(res => {
        if (res.code === 200) {
          const newItem = { ...item }
          newItem.x = x
          newItem.y = y
          const { id, name } = item
          this.currentId = id
          const newPlayGound = [...this.playGround]
          const currentIndex = newPlayGound.findIndex(t => t.id === id)
          this.currentDeviceName = name
          newPlayGound[currentIndex] = newItem
          this.playGround = [...newPlayGound]
        }
      })
    },

    saveFunc() {
      const vm = this
      vm.currentDeviceName = null
      vm.currentId = null
      vm.$nextTick(() => {
        const dom = vm.$refs.takePhoto
        html2canvas(dom, {
          useCORS: true
        }).then(function(canvas) {
          const base64Url = canvas.toDataURL('image/png')
          vm.thumbnailImage = base64Url
        })
      })
    },

    // 获取可选择的点和图片上的点
    getGalleryDevice() {
      const params = {
        companyId: this.id,
        distributionId: this.currentGalleryId
      }
      getGalleryDevice(params).then(result => {
        this.classRoom = result.data
        this.playGround = findPlaygound([...result.data])
      })
    },

    // 配电图列表
    getGalleryList() {
      const vm = this
      const params = { companyId: vm.id }
      getGalleryList(params).then(res => {
        if (res.code === 200) {
          this.galleryList = res.data
        } else {
          this.galleryList = []
        }
      })
    }
  }
}
</script>

